'use strict';

//百度地图标注相关商家
// 引入一个etc 注册map map 为相应的百度地图操作 
//初始化 引入定义的config 注册用户所在地址的经纬度
//返回一个etc.map  包含所有的地图操作.

var Etc = {};
(function (Etc) {
    //初始化参数
    var Etc = Etc || {}; //一个函数,带有map的各种操作信息
    var allShopList = null;//传入所有的商铺
    var avaibleShopList = null;//刷选出来可显示的商铺
    var cityShopList = [];//刷选出来的当前城市的商铺
    var serverList = [];//选择的服务,用来刷选地图上的商铺
    var mapCity = '';//当前城市
    var zoomLeve = 13;//缩放比例
    var juhe = false;//用来判断是否进入聚合状态
    Etc.Map = function () {
        var map = null,
            mapimgSrc = './app/Tpl/main/fanwe/images/map/',
            icon_4s = mapimgSrc + 'icon_4s.png',//4s店地图logo
            icon_xiu = mapimgSrc + 'icon_xiu.png',//维修厂的logo
            icon_dian = mapimgSrc + 'icon_dian.png',//快修店的logo
            bIcon_4s = new BMap.Icon(icon_4s, new BMap.Size(20, 25), {
                imageOffset: new BMap.Size(0, 0)
            }),
            bIcon_dian = new BMap.Icon(icon_dian, new BMap.Size(20, 25), {
                imageOffset: new BMap.Size(0, 0)
            }),
            bIcon_xiu = new BMap.Icon(icon_xiu, new BMap.Size(20, 25), {
                imageOffset: new BMap.Size(0, 0)
            });
        function _init(config) {
            console.log('etcMap init');
            //配置地图基本设置
            map = new BMap.Map(config.map || "allmap");
            map.setMinZoom(8);
            mapCity = config.city;
            map.centerAndZoom(config.city, zoomLeve);
            map.enableScrollWheelZoom(true);
            map.enableDragging();
            map.addControl(new BMap.OverviewMapControl());
            var opts = { anchor: BMAP_ANCHOR_TOP_RIGHT, offset: new BMap.Size(10, 10) }; //修改NavigationControl()的显示位置
            map.addControl(new BMap.NavigationControl(opts)); //地图平移缩放控件，默认位于地图左上方，它包含控制地图的平移和缩放
            map.addEventListener('zoomend', zoomTrigger);
            map.addEventListener("dragend", showVisibleShop);
        }
        //根据缩放比触发显示商店
        function zoomTrigger() {
            //根据缩放比率的不同,显示不同的商店或者聚合商店位置
            var zoom = map.getZoom();
            console.log('zoom:' + zoom);
            if (zoom <= 9) {
                //显示省级聚合
                juhe = true;
                map.clearOverlays();
                console.log('省聚合')
                showProvincePoly();
            } else if (zoom <= 10) {
                //显示市级别聚合
                console.log('城市聚合')
                juhe = true;
                map.clearOverlays();
                _showCityPoly();
            } else {
                //显示商店
                juhe = false;
                map.clearOverlays(); //清除覆盖物
                showVisibleShop();
            }
        }
        //显示省级别聚合
        function showProvincePoly() {
            if (avaibleShopList != null) {
                var provinceName = "山东省";
                var length = avaibleShopList.length;
                var html = `<div class="marker-box">
                                    <h6>${provinceName}</h6>
                                    <p>${length}
                                        <small>家</small>
                                    </p>
                                </div>`;
                var point = new BMap.Point(117.109655, 36.75054);
                var richMarker = new BMapLib.RichMarker(html, point);
                map.addOverlay(richMarker);
                richMarker.addEventListener("click", function (e) {
                    map.centerAndZoom(new BMap.Point(e.currentTarget._position.lng, e.currentTarget._position.lat), 10);
                });
                //
            }
        }
        /**
         * 显示城市的聚合
         * @param {Array} shoplist 
         */
        function _showCityPoly(shoplist) {
            let tempCity = [];
            let cityArray = [];
            if (allShopList == null) {
                allShopList = shopList;
            }
            avaibleShopList = allShopList;
            //循环数组,根据城市进行刷选
            avaibleShopList.forEach((item, index) => {
                tempCity.push(item['city_id']);
            })
            tempCity.sort((a, b) => {
                return a - b
            });
            var temp, cityIndex;
            tempCity.forEach((item, index) => {
                if (index == 0) {
                    cityArray.push({
                        cityId: item,
                        num: 1
                    })
                    temp = item,
                        cityIndex = 0;
                } else {
                    if (temp == item) {
                        cityArray[cityIndex].num += 1;
                    } else {
                        cityArray.push({
                            cityId: item,
                            num: 1
                        })
                        cityIndex += 1;
                    }
                }
            })
            //在地图上标记出来相应的标记
            cityArray.forEach((shop, index) => {
                let cityName;
                if (shop.cityId == '22') {
                    cityName = '济南';
                }
                let html = `<div class="marker-box">
                                <h6>${cityName}</h6>
                                <p>${shop.num}
                                    <small>家</small>
                                </p>
                            </div>`;
                var point = new BMap.Point(117.109655, 36.75054);
                var richMarker = new BMapLib.RichMarker(html, point);
                map.addOverlay(richMarker);
                richMarker.addEventListener("click", function (e) {
                    map.centerAndZoom('济南', 12);
                });
            })
        }
        //刷选出来可以用来显示的店铺,然后交给AddShopMarker来显示
        function showVisibleShop() {
            let tempArray = [];
            if(serverList.length > 0) {
                avaibleShopList.forEach((item, index)=>{
                    let shopServer = item.deal_cate_match_row.split(',');
                        shopServer.shift();
                    let test = array_same(shopServer,serverList)
                    if(test.length == serverList.length) {
                        tempArray.push(item);
                    }

                })
            } else {
                tempArray = avaibleShopList;
            }
            if (map != null && tempArray != null && juhe == false) {
                var bound = map.getBounds();
                tempArray.forEach(function (shop, index) {
                    //获得当前区域的范围 判断是否在同一个范围,如果是,显示图片
                    if (shop.xpoint) {
                        var point = new BMap.Point(shop.xpoint, shop.ypoint);
                    }
                    var isVisible = BMapLib.GeoUtils.isPointInRect(point, bound);
                    if (isVisible) {
                        AddShopMarker(shop);
                    }
                });
            }
        }
        /**
         * 在地图上标记商店 以及显示相应的点击弹窗
         * @param {Object} shop shop的详细信息
         * @returns null
         */
        function AddShopMarker(shop) {
            var markInfo = shop,
                icon = '';
            //根据shop的类型选择不同的标注图标
            switch(shop.is_type) {
                case "0":
                    icon = bIcon_xiu;
                    break;
                case "1":
                    icon = bIcon_4s;
                    break;
                case "2":
                    icon = bIcon_dian;
                    break;
            }
            var marker, //标记
                infoWindow; //窗口
            var point = new BMap.Point(markInfo.xpoint, markInfo.ypoint);
            var marker = new BMap.Marker(point, {
                icon: icon
            });
            if (marker.name != "" || marker.name != null) {
                /**
                 * 显示相关的商户信息
                 */
                var showInfo = function showInfo() {
                    setMapCenterByPoint(point);
                    infoWindow = new BMap.InfoWindow();
                    var str = getShopContent(markInfo);
                    infoWindow.setHeight(650);
                    infoWindow.setWidth(400);
                    infoWindow.setTitle(getTitleContent(markInfo.name));
                    infoWindow.setContent(str);
                    map.openInfoWindow(infoWindow, point); //开启信息窗口
                };

                map.addOverlay(marker);

                marker.addEventListener('click', function () {
                    showInfo();
                });
                //当信息窗口关闭时内容
                marker.addEventListener("close", function () {
                    //关闭时清除，减少资源使用
                    infoWindow.setTitle("");
                    infoWindow.setContent("");
                });
            }
        }
        /**
         * 设置title的html or css 样式
         * @param {String} title 传递的标题信息
         * return {String} 设置了html 和css的string 
         */
        function getTitleContent(title) {
            var title = title;
            var newTitle = "<p class='shop-info-title'>" + title + "</p>";
            return newTitle;
        }
        /**
         * 根据传递过来的class生成html
         * @param {object} markInfo 
         * @returns {str} 显示商家的评价以及信息的string
         */
        function getShopContent(markInfo) {
            var commentStr = createComment(markInfo);
            var payTest = markInfo.dc_online_pay;
            var payClass = '';
            if (payTest.indexOf('1') != -1) {
                payClass += '<i class="i-shop i-cash"></i>';
            }
            if (payTest.indexOf('0') != -1) {
                payClass += '<i class="i-shop i-alipay"></i>';
            }
            if (payTest.indexOf('2') != -1) {
                payClass += '<i class="i-shop i-bank"></i>';
            }
            var newStr = `<div class="shop-info-content">
            <div class="clearOver">
                <div class="f_l">
                    <img class="shop-info-content-logo" src="${markInfo.preview}">
                </div>
                <div class="f_l shop-info-content-infobox">
                    <p>
                        <span>营业时间:</span>${markInfo.open_time}</p>
                    <p>
                        <span>支付方式:${payClass}</span>
                    </p>
                    <p>
                        <span>服务支持:</span>
                    </p>
                    <p>
                        <span>门店地址:${markInfo.address}</span>
                    </p>
                    <div class="gray-border"></div>
                    <div>
                        <a href="./index.php?ctl=tire" class="red-button">去买轮胎</a>
                        <a href=".index.php?ctl=dc" class="red-button">去做保养</a>
                    </div>
                </div>
            </div>
            <div class="shop-comment-box">
                ${commentStr}
            </div>
        </div>`;
            return newStr;

        }
        /**
         * 根据商家,选择生成相应的评论
         * @param {obj} shop 传入的商家
         * @return Str 生成的商家评论
         */
        function createComment(shop) {
            //根据商家创建服务
            let url = 'index.php?ctl=position&act=supplier_review_list&location_id=' + shop.id;
            let countnum = shop['avg_point'].substr(0, 3);
            let comments = '';
            //根据服务类型创建评论
            $.ajax({
                url: url,
                async: false,
                success: function (data) {
                    let temparr = data;
                    temparr = JSON.parse(data);
                    temparr.forEach((item, index) => {
                        let point = item.point;
                        let starHtml = createStar(point);
                        //返回星级评价的字符串

                        //处理过长的评论
                        let tempcomment = item.content;
                        if (tempcomment.length > 10) {
                            tempcomment = tempcomment.substr(0, 10) + '...';
                        }
                        comments += `<div class="user-comment">
                                        <img class="user-logo" src="${item['user_list'].avatar}">
                                        <div class="line">
                                            <span>${item['user_list']['user_name']}</span>
                                            ${starHtml}
                                            <span class="f_r">${item['create_time_format']}</span>
                                        </div>
                                        <div class="line">
                                            ${tempcomment}
                                        </div>
                                    </div>`;

                    })
                    if (comments == '') {//暂无评论
                        comments = "暂无评论";
                    }
                }
            })
            let all = `<div class="shop-comment-box">
                            <div class="shop-comment">
                                <div class="comment-title comment-title-active">用户评论
                                    <span>${countnum}</span>
                                </div>
                            </div>
                            <div class="shop-comment-info">
                                ${comments}
                            </div>
                        </div>`;
            return all;
        }
        /**
         * 根据传递的数值不同生成不同的星星数目
         * @param {str}输入的数字
         * @return {str}
         */
        function createStar(num) {
            let star = parseInt(num) * 20;
            let html = `<span class="i-shop star">
                            <i class="i-shop" style="width: ${star}%;"></i>
                        </span>`;
            return html;
        }
        /**
         * 接受传入的后台商店数据,注册相应的时间以及处理出来所有的AllShop
         * @param {Array} shopList 
         * @return Null
         */
        function _rander(shopList) {
            if (allShopList == null) {
                allShopList = shopList;
            }
            avaibleShopList = allShopList;
            if (cityShopList.length == 0) {//如果初始化没有根据当前城市刷选出来数组,就进行刷选
                allShopList.forEach((item, index) => {
                    if (item.city_name == mapCity) {
                        cityShopList.push(item);
                    }
                })
            }
        }
        /**
         * 返回一个在百度地图的定位点
         * @returns 百度地图定位点
         */
        function setMapCenterByPoint(PointObject) {
            var testZoom = map.getZoom();
            console.log(testZoom);
            if (testZoom < 16) {
                map.setCenter(PointObject); //设置中心点
                map.centerAndZoom(PointObject, 16); //设置中心点和扩大比例
            }
        }
        /**
         * 生成推荐的商户列表
         * @param {array} shopList 接受的商户列表
         * 
         */
        function showShopList(shopList) {

            let $shopBox = $('.shop-list-box');
            $shopBox.empty();
            let html;
            shopList.forEach((shop) => {
                var payTest = shop['dc_online_pay'];
                var payClass = '';
                if (payTest.indexOf('1') != -1) {
                    payClass += '<i class="i-shop i-cash"></i>';
                }
                if (payTest.indexOf('0') != -1) {
                    payClass += '<i class="i-shop i-alipay"></i>';
                }
                if (payTest.indexOf('2') != -1) {
                    payClass += '<i class="i-shop i-bank"></i>';
                }
                var count = shop.avg_point.substr(0, 3);
                html = `<div class="shop-item clearOver"  data-pay="${shop['dc_online_pay']}" data-id="${shop.id}" data-xpoint="${shop.xpoint}" data-ypoint="${shop.ypoint}" data-name="${shop.name}" data-address="${shop.address}" data-preview="${shop.preview}" data-open_time="${shop.open_time}" data-avg_point="${shop['avg_point']}">
                            <p class="title">
                                <span>${shop.name}</span>
                            </p>
                            <div class="logo f_l">
                                <img src="${shop.preview}" alt="">
                            </div>
                            <div class="content f_l">
                                <p>一共安装<span class="red">${shop.order_count}</span>单<span class="commont-num">评价<span class="red">${count}</span></span></p>
                                <p>门店地址: <span class="black">${shop.address}</span></p>
                                <p>支付方式:${payClass} </p>
                            </div>
                        </div>`;
                $shopBox.append(html);
                html = '';

            })
            $('.shop-item').click(function (e) {
                let id = $(this).attr('data-id'),
                    xpoint = $(this).attr('data-xpoint'),
                    ypoint = $(this).attr('data-ypoint'),
                    name = $(this).attr('data-name'),
                    address = $(this).attr('data-address'),
                    preview = $(this).attr('data-preview'),
                    open_time = $(this).attr('data-open_time'),
                    dc_online_pay = $(this).attr('data-pay'),
                    avg_point = $(this).attr('data-avg_point');
                let shop = {
                    id: id,
                    xpoint: xpoint,
                    ypoint: ypoint,
                    name: name,
                    address: address,
                    preview: preview,
                    dc_online_pay: dc_online_pay,
                    open_time: open_time,
                    avg_point: avg_point
                }
                //在地图上显示标记

                ShopMarker(shop);
            })
        }
        /**
        * 在地图上显示标记商店 以及显示相应的点击弹窗
        * @param {Object} shop shop的详细信息
        * @returns null
        */

        function ShopMarker(shop) {
            var markInfo = shop;
            //根据shop的类型选择不同的标注图标
            let icon = bIcon_dian;
            var marker, //标记
                infoWindow; //窗口
            var point = new BMap.Point(markInfo.xpoint, markInfo.ypoint);
            var marker = new BMap.Marker(point, {
                icon: icon
            });
            if (marker.name != "" || marker.name != null) {
                /**
                 * 显示相关的商户信息
                 */
                var showInfo = function showInfo() {
                    setMapCenterByPoint(point);
                    infoWindow = new BMap.InfoWindow();
                    var str = getShopContent(markInfo);
                    infoWindow.setHeight(650);
                    infoWindow.setWidth(400);
                    infoWindow.setTitle(getTitleContent(markInfo.name));
                    infoWindow.setContent(str);
                    map.openInfoWindow(infoWindow, point); //开启信息窗口
                };
                map.centerAndZoom(point, 16)
                map.addOverlay(marker);

                showInfo();
                //当信息窗口关闭时内容
                marker.addEventListener("close", function () {
                    //关闭时清除，减少资源使用
                    infoWindow.setTitle("");
                    infoWindow.setContent("");
                });
            }
        }
        /**
         * 初始化点击搜索
         */
        function initSearch() {
            //输入时找出匹配的商户
            $('#js-search').on('input', (e) => {
                let shops = avaibleShopList;
                let word = $(e.target).val();//输入的关键字
                let $showShop = $('#shop-word');//显示搜索结果的地方
                if (word <= 0) {
                    $showShop.empty();
                    return
                }
                let temp = [];//刷选出来符合要求的店铺名称
                shops.forEach((_shop) => {
                    if (_shop.name.indexOf(word) != -1) {
                        temp.push(_shop);
                    }
                })

                //为刷选出来的店铺增加样式
                temp.forEach((shop) => {
                    let tempArr = shop.name.split(word);
                    let shopStr = "";
                    let shophtml = "";
                    for (let i = 0; i < tempArr.length; i++) {
                        if (i == 0) {
                            shopStr += `<span class="searchWord">${word}</span>`;
                        } else {
                            shopStr = shopStr + tempArr[i];
                        }
                    }
                    shophtml = `<a>${shopStr}</a>`;
                    $(shophtml).appendTo($showShop)
                });

                $showShop.on('click', 'a', function (e) {
                    let word = $(this).text();
                    $('#js-search').val(word);
                    $showShop.empty();
                });
                let $jsInput = $('#js-search');
                $("#js-search-button").on('click', (e) => {
                    let val = $jsInput.val();
                    let temp;
                    shops.forEach(function (shop) {
                        if (shop.name == val) {
                            temp = shop;
                            return;
                        }
                    })
                    //定位到选择出来的店铺
                    ShopMarker(temp);
                })
            })
        }
        /**
         * 由高到底的排出订单
         * @param {arr} arr 传入的商铺
         * @returns {array} 排序后的数组
         */
        function quicksortGoods(arr) {
            if (arr.length <= 1) {
                return arr;
            }
            var point = arr.splice(Math.floor(arr.length / 2), 1)[0];
            let left = [];
            let right = [];
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].order_count > point.order_count) {
                    left.push(arr[i]);
                } else {
                    right.push(arr[i]);
                }
            }
            return quicksortGoods(left).concat(point, quicksortGoods(right));
        }
        /**
         * 由高到底的排出评分
         * @param {arr} arr 传入的商铺数组 
         * @returns {array} 排序后的数组
         */
        function quicksortGrade(arr) {
            if (arr.length <= 1) {
                return arr;
            }
            var point = arr.splice(Math.floor(arr.length / 2), 1)[0];
            let left = [];
            let right = [];
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].avg_point > point.avg_point) {
                    left.push(arr[i]);
                } else {
                    right.push(arr[i]);
                }
            }
            return quicksortGrade(left).concat(point, quicksortGrade(right));
        }
        /**
         * 根据条件不同刷选渲染出来不同的左侧商铺信息
         * @param {str} condition 刷选条件
         * @param {str} city 传入的城市
         * @param {str} shopSort 排序条件
         * 
         */
        function filterShopList(condition, shopSort, city) {
            let conditionTest = '',
                tempArr = [];
            if (city == null && condition == null && shopSort == null) {//初始化调用
                showShopList(cityShopList);
                return;
            }
            //判断城市是否更改
            if (city != null && city != mapCity) {//切换城市
                mapCity = city;
                //设置百度地图到新的城市
                map.centerAndZoom(mapCity, zoomLeve);
                //更新当前城市数组
                cityShopList = [];
                allShopList.forEach((item, index) => {
                    if (item.city_name == mapCity) {
                        cityShopList.push(item);
                    }
                })
            }
            //判断条件 是刷选不同类型的门店,还是对门店进行排序
            if (condition != null) {//判断选择门店
                if (condition == '4S店' || condition == '维修厂' || condition == '所有类型' || condition == '快修店') {
                    switch (condition) {
                        case '4S店':
                            conditionTest = 1;
                            break;
                        case '维修厂':
                            conditionTest = 0;
                            break;
                        case '快修店':
                            conditionTest = 2;
                            break
                        case '所有类型':
                            conditionTest = 3;
                            break;
                    }
                    if(conditionTest == 3) {
                        tempArr = cityShopList;
                    }else{
                        cityShopList.forEach((item, index) => {
                            if (item.is_type == conditionTest) {
                                tempArr.push(item);
                            }
                        })
                    }
                }
            }
            switch (shopSort) {
                case '综合排序':
                    showShopList(tempArr);
                    break;
                case '满意度':
                    tempArr = quicksortGrade(tempArr);
                    showShopList(tempArr);
                    break;
                case '累计安装':
                    tempArr = quicksortGoods(tempArr);
                    showShopList(tempArr);
                    break
            }

        }
        //根据点击选择服务刷选店铺
        $('.js-service').click(function(e){
            var text = $(this).text();
            $(this).toggleClass('active');
            if(serverList.indexOf(text)!= -1) {
                serverList.splice(serverList.indexOf(text),1);
            }else {
                serverList.push(text);
            }
            //重置Bmap上的店铺
            if(!juhe) {
                map.clearOverlays(); 
                showVisibleShop();
            }
        })
        /**
         * 返回两个数组中相同的数值的集合
         * @param {arr} a 传入的数组 
         * @param {arr} b 传入的数组
         * @returns 返回两个数组相似的地方
         */
        function array_same(a, b) {
            var result = [];
            for(var i = 0; i < b.length; i ++) {
                var temp = b[i];
                for(var j = 0; j < a.length; j ++) {
                    if(temp === a[j]) {
                        result.push(temp);
                        break;
                    }
                }
            }
            return result
        }
        return {
            init: function init(config) {
                _init(config);
            },
            rander: function rander(shopList) {
                _rander(shopList);
            },
            showShopList: showShopList,
            initSearch: initSearch,
            filterShopList: filterShopList
        };
    }();
})(Etc);
